package com.xuzy.x808.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AccessServer {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    @Qualifier("bossGroup")
    private NioEventLoopGroup bossGroup;

    @Autowired
    @Qualifier("workerGroup")
    private NioEventLoopGroup workerGroup;

    @Autowired
    @Qualifier("businessGroup")
    private EventExecutorGroup businessGroup;

    @Autowired
    private JT808ChannelInitializer jt808ChannelInitializer;

    @Value("${accessServer.port}")
    private int port;

    @PostConstruct
    public void start() throws Exception {
        logger.info("正在启动808接入服务>>>>>>>>>>>>>>>>>>>>");

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class) //指定NIO的模式.NioServerSocketChannel对应TCP, NioDatagramChannel对应UDP
                .handler(new LoggingHandler(LogLevel.INFO))
                .option(ChannelOption.SO_BACKLOG, 1024) // 设置TCP缓冲区
                .childOption(ChannelOption.SO_SNDBUF, 32 * 1024) // 设置发送缓冲大小
                .option(ChannelOption.SO_RCVBUF, 32 * 1024) // 这是接收缓冲大小
                .childOption(ChannelOption.SO_KEEPALIVE, true) // 保持连接
                .childHandler(jt808ChannelInitializer);

        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        if (channelFuture.isSuccess()) {
            logger.info("808接入服务已启动，port：{}>>>>>>>>>>>>>>>>>>>", port);
        }

    }

    public void stop() {
        logger.info("正在关闭808接入服务>>>>>>>>>>>>>>>>>>>>");

        bossGroup.shutdownGracefully();
        bossGroup = null;

        workerGroup.shutdownGracefully();
        workerGroup = null;

        businessGroup.shutdownGracefully();
        businessGroup = null;

        logger.info("808接入服务已关闭>>>>>>>>>>>>>>>>>>>>");
    }
}
